package com.wpml;

import com.wpml.annotation.Param;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Map;

/**
 * @Description
 * @Date 2021-08-19
 * @Author wangpei
 **/
@WebServlet(urlPatterns = "*.do")
public class DispatcherServlet extends HttpServlet {

    /**
     * 参数构建
     * @param parameterTypes
     * @return
     */
    private Object[] buildArgs(Class<?>[] parameterTypes) throws IllegalAccessException, InstantiationException {
        Object[] args = new Object[parameterTypes.length];

        int index = 0;
        HttpServletRequest request = ContextThreadLocal.getRequest();
        for (Class<?> type : parameterTypes) {
            if (type == HttpServletRequest.class) {
                args[index] = request;
            } else if (type == HttpServletResponse.class) {
                args[index] = ContextThreadLocal.getResponse();
            } else {
//                boolean flag = false;
                for (Class<?> beanClass : BeanFactory.getBeanList()) {
                    Object bean = beanClass.newInstance();
                    if (type == beanClass) {
                        Field[] beanFields = beanClass.getDeclaredFields();
                        for (Field bf : beanFields) {
                            String parameter = request.getParameter(bf.getName());
                            if (parameter != null) {
                                bf.setAccessible(true);
                                if (bf.getType() == String.class) {
                                    bf.set(bean, parameter);
                                }
                                if (bf.getType() == Integer.class || bf.getType() == Integer.TYPE) {
                                    bf.set(bean, Integer.valueOf(parameter));
                                }
                            }
                        }
                        args[index] = bean;
//                        flag = true;
                        break;
                    }
                }

                /*if (!flag) {
                    Map<String, String[]> parameterMap = request.getParameterMap();
                    Param[] declaredAnnotationsByType = type.getDeclaredAnnotationsByType(Param.class);
                    Param[] annotationsByType = type.getAnnotationsByType(Param.class);
                    String value = annotationsByType[0].value();
                    System.out.println(value);
                }*/
            }
            index++;
        }

        return args;
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestURI = req.getRequestURI();
        System.out.println(requestURI);
        try {

            // 设置线程域对象
            ContextThreadLocal.setServletContextThreadLocal(new ServletContextBean(req, resp));

            BeanMateData beanMateData = BeanFactory.getBeanMateData(requestURI.substring(requestURI.lastIndexOf("/"), requestURI.lastIndexOf(".")));

            Class<?>[] parameterTypes = beanMateData.getParameterTypes();

            Object[] args = buildArgs(parameterTypes);

            beanMateData.getMethod().invoke(beanMateData.getClazz().newInstance(), args);


            /*Class<?> clazz = Class.forName("com.wpml.UserController");

            Method method = clazz.getDeclaredMethod("login", HttpServletRequest.class, HttpServletResponse.class);

            method.invoke(clazz.newInstance(), req, resp);*/


        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
